package com.drought.rained.ui.activity.repayment;

import android.annotation.SuppressLint;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.drought.rained.R;
import com.drought.rained.base.BaseTitleActivity;
import com.drought.rained.bean.PayCodeDataLJ;
import com.drought.rained.business.RouterMapLJ;
import com.drought.rained.common.ConstantLJ;
import com.drought.rained.mvpview.PayMvpViewLJ;
import com.drought.rained.presenter.PayPresenterLJ;
import com.drought.rained.response.PayCodeResponseLJ;
import com.drought.rained.utils.StringUtilsLJ;
import com.drought.rained.utils.ToastUtilsLJ;

import butterknife.BindView;
import butterknife.ButterKnife;

@SuppressLint("CheckResult")
@Route(name = "ATM还款",path = RouterMapLJ.REPAY_OTC_PAGE)
public class PayOTCActivityLJ extends BaseTitleActivity implements PayMvpViewLJ, View.OnClickListener {

    @BindView(R.id.tv_pay_num)
    TextView tvPayNum;
    @BindView(R.id.tv_pay_code_permata)
    TextView tvPayCodePermata;
    @BindView(R.id.tv_countdown_view)
    TextView tvCountdownView;
    @BindView(R.id.btn_refresh)
    Button btnRefresh;
    @BindView(R.id.tv_pay_guide)
    TextView tvPayGuide;

    private String mOrderId;
    private String mOrderMoneyNum;
    private boolean isRollover;
    private PayCodeDataLJ mPaycodeData;
    private CountDownTimer countDownTimer;
    private boolean isStartCountDown = false;
    private PayPresenterLJ payPresenter;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        setRightText(getStringResource(R.string.pay_atm_hint));
        btnRefresh.setOnClickListener(this);
        tvPayGuide.setOnClickListener(this);
        setRigthListener(this);
    }

    @Override
    protected void onUIReady() {
        if (getIntent() == null || StringUtilsLJ.isEmpty(getIntent().getStringExtra(ConstantLJ.ORDER_ID))) {
            ToastUtilsLJ.showShort(PayOTCActivityLJ.this, getStringResource(R.string.illegal_params));
            return;
        }
        payPresenter = new PayPresenterLJ(this);
        mOrderId = getIntent().getStringExtra(ConstantLJ.ORDER_ID);
        mOrderMoneyNum = getIntent().getStringExtra(ConstantLJ.ORDER_MONEY_NUM);
        isRollover = getIntent().getBooleanExtra(ConstantLJ.ORDER_MONEY_IS_ROLLOVER, false);
        if (!StringUtilsLJ.isEmpty(mOrderMoneyNum)) {
            tvPayNum.setText(getStringResource(R.string.loan_rapid_money_hint)
                    + StringUtilsLJ.getDotMoneyStr(mOrderMoneyNum));
        }

        getRepayCodeData();
    }

    @Override
    protected int getContentResId() {
        return R.layout.layout_of_pay_otc;
    }

    @Override
    public String getPageTitle() {
        return getStringResource(R.string.pay_otc_page_title);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_pay_guide:
                ARouter.getInstance().build(RouterMapLJ.PAY_GUIDE_PAGE).navigation();
                break;
            case R.id.btn_refresh:
                if (mPaycodeData == null || !isStartCountDown) {
                    getRepayCodeData();
                    return;
                }
                break;
            default:
                ARouter.getInstance().build(RouterMapLJ.REPAY_ATM_PAGE)
                        .withString(ConstantLJ.ORDER_ID, mOrderId)
                        .withString(ConstantLJ.ORDER_MONEY_NUM, mOrderMoneyNum)
                        .withBoolean(ConstantLJ.ORDER_MONEY_IS_ROLLOVER, isRollover).navigation();
                finish();
                break;
        }
    }

    public void getRepayCodeData() {
        if (StringUtilsLJ.isEmpty(mOrderId)) return;
        showLoadingView();
        if (isRollover) {
            payPresenter.getRolloverPayCodeData(mOrderId);
        } else {
            payPresenter.getPayCodeData(mOrderId);
        }
    }

    private void fillView(PayCodeDataLJ payCodeData) {
        if (payCodeData == null) {
            getRepayCodeData();
            return;
        }
        if (tvPayCodePermata != null) {
            tvPayCodePermata.setText(payCodeData.getPayCodeBean().getOtcCode());
        }
        if (countDownTimer == null) {

            if (btnRefresh != null) {
                btnRefresh.setEnabled(false);
            }
            isStartCountDown = true;

            countDownTimer = new CountDownTimer(payCodeData.getTimeSeconds() * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {


                    if (tvCountdownView != null) {
                        StringBuilder builder = new StringBuilder(getStringResource(R.string.pay_code_remain_time_hint));
                        builder.append("  ");
                        builder.append(getFormatTime(millisUntilFinished));
                        tvCountdownView.setText(builder.toString());

                    } else {
                        this.cancel();
                        countDownTimer = null;
                        isStartCountDown = false;
                        btnRefresh.setEnabled(true);
                    }
                }

                @Override
                public void onFinish() {
                    tvCountdownView.setText(getResources().getString(R.string.pay_code_lose_hint));
                    isStartCountDown = false;
                    btnRefresh.setEnabled(true);
                    countDownTimer = null;
                }
            }.start();
        }
    }

    StringBuilder timeStr = new StringBuilder();

    private String getFormatTime(long millisUntilFinished) {
        timeStr.delete(0, timeStr.length());

        if (millisUntilFinished < 0) return "";
        Long day = millisUntilFinished / (1000 * 60 * 60 * 24);   //以天数为单位取整
        Long hour = (millisUntilFinished / (60 * 60 * 1000) - day * 24);    //以小时为单位取整
        Long min = ((millisUntilFinished / (60 * 1000)) - day * 24 * 60 - hour * 60); //以分钟为单位取整
        Long second = (millisUntilFinished / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);//秒

        if (day > 0) {
            timeStr.append(day).append(":");
        }
        if (hour > 0 || (hour == 0 && timeStr.length() > 0)) {
            timeStr.append(hour).append(":");
        }
        if (min > 0 || (min == 0 && timeStr.length() > 0)) {
            timeStr.append(min).append(":");
        }
        timeStr.append(second);

        return timeStr.toString();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    public void onGetDataNext(PayCodeResponseLJ payCodeResponse) {
        dismissLoadingView();
        if (payCodeResponse.getStatus() == ConstantLJ.HTTP_OK) {
            mPaycodeData = payCodeResponse.getData();
            fillView(payCodeResponse.getData());

        } else {
            ToastUtilsLJ.showShort(PayOTCActivityLJ.this, payCodeResponse.getMessage());
        }
    }

    @Override
    public void onGetDataError(Throwable throwable) {
        dismissLoadingView();
    }
}
